<!--工程管理主界面-->

<template>
  <div class="project-manage">
<!--    <Spin fix v-show="loading">
      <Icon type="ios-loading" size=18 class="spin-icon-load"></Icon>
      <div>加载中，请耐心等待...</div>
    </Spin>-->
    <div class="project-toolbar">
      <Button class="m-r-5px" type="primary" @click="openProjectForm('add')">
        <Icon type="md-add"/>
        新建工程
      </Button>
      <Tooltip placement="top" content="刷新数据">
        <Button class="m-r-5px" type="primary" @click="loadProjects();loadPages()">
          <Icon type="md-refresh"/>
        </Button>
      </Tooltip>
      <span style="font-size: 14px;" v-if="currentUser.role_code == 'ROLE_ADMIN'">
        工程总数：{{statisticsData.projectTotalCount}}；页面总数：{{statisticsData.pageTotalCount}}
      </span>
      <div class="float-right">
        <Select ref="projectSelect" v-model="pageParam.project_id" clearable filterable style="width: 250px;"
                placeholder="请选择工程" @on-change="clearSearch">
          <Option v-for="project in projectList" :value="project.id" :key="project.id" :label="project.name">
            <Tooltip content="协同开发工程" placement="left" :disabled="project.user_id == currentUser.id">
            <span style="font-size: 14px;">
              <Icon style="margin-top: -2px;" v-if="project.user_id != currentUser.id" custom="iconfont icon-synergy"
                    size="18"/> {{ project.name }}
            </span>
            </Tooltip>
            <p style="color:#ccc">{{ project.remark }}</p>
          </Option>
        </Select>
        <Button class="m-l-5px" @click="openProject" :disabled="!pageParam.project_id">进入设计器</Button>
        <Dropdown @on-click="otherDropdownClickHandle">
          <Button class="m-l-5px">
            操作
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="editProject" :disabled="!pageParam.project_id || isSynergyProject">编辑工程基本信息</DropdownItem>
            <DropdownItem name="openImportPage" :disabled="!pageParam.project_id">导入页面</DropdownItem>
            <DropdownItem name="openProjectDeveloperList" :disabled="!pageParam.project_id">协同开发者</DropdownItem>
            <DropdownItem name="deleteProject" :disabled="!pageParam.project_id || isSynergyProject" divided style="color: #f44336;">删除工程
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>

      <div class="clearfix"></div>
      <div class="m-b-10px"></div>
      <div class="page-search-wrap">
        <Input v-model="pageParam.name" class="m-r-5px" style="width: 250px;" placeholder="页面名称" @on-enter="loadPages"/>
        <Select v-model="pageParam.develop_canvas" class="m-r-5px" clearable style="width: 120px;" placeholder="布局类型">
          <Option value="AbsoluteLayoutCanvas">绝对布局</Option>
          <Option value="ReactiveLayoutCanvas">响应式栅格布局</Option>
        </Select>
        <Select v-model="pageParam.publish" class="m-r-5px" clearable style="width: 90px;" placeholder="状态">
          <Option value="1">已发布</Option>
          <Option value="0">未发布</Option>
        </Select>
        <Button class="m-r-5px" @click="loadPages">
          <Icon type="md-search"/>
          搜索
        </Button>
        <Button class="m-r-5px" @click="clearSearch">清空</Button>
      </div>

    </div>

    <div class="m-b-10px"></div>

    <div class="page-container">
      <Row :gutter="15">
        <i-col v-for="page in pageList" :key="page.id" :xs="24" :sm="12" :md="12" :xl="6" :xxl="4">
          <div class="page-card">
            <div class="img-wrap">
              <img v-if="page.thumbnail" class="page-thumbnail" :src="$PnUtil.buildImageSrc(page.thumbnail)"/>
              <Icon v-else class="default-img-icon"
                    :custom="developCanvasIcon(page.develop_canvas)"/>
              <div v-if="page.thumbnail" class="layout-type">
                <Tooltip :content="developCanvasName(page.develop_canvas)" placement="left">
                  <Icon :custom="developCanvasIcon(page.develop_canvas)"/>
                </Tooltip>
              </div>
              <div class="operation-wrap">
                <Button type="primary" @click="openPageDesigner(page.id)">
                  <Icon custom="iconfont icon-design"/>
                  设计
                </Button>
                <div class="operation-btns-wrap">
                  <Tooltip content="预览" placement="top">
                    <a href="javascript:;" @click="previewPage(page.id, page.path)">
                      <Icon custom="iconfont icondesktop" size="18"/>
                    </a>
                  </Tooltip>
                  <Tooltip content="发布" placement="top">
                    <a href="javascript:;" @click="openReleasePageFormModal(page.id)">
                      <Icon custom="iconfont icon-send" size="18"/>
                    </a>
                  </Tooltip>
                  <Tooltip content="导出" placement="top">
                    <a href="javascript:;" @click="exportPage(page.id)">
                      <Icon custom="iconfont icon-download" size="18"/>
                    </a>
                  </Tooltip>
                  <Tooltip content="复制链接" placement="top">
                    <a href="javascript:;" @click="copyLink(page.path)">
                      <Icon custom="iconfont icon-copy-link" size="18"/>
                    </a>
                  </Tooltip>
                  <Tooltip content="拷贝" placement="top">
                    <a href="javascript:;" @click="copyPage(page.id)">
                      <Icon type="md-copy" size="18" style="top: 3px;"/>
                    </a>
                  </Tooltip>
                  <Tooltip content="删除" placement="top">
                    <a href="javascript:;" @click="deletePage(page.id)">
                      <Icon type="md-trash" size="18" style="top: 3px;"/>
                    </a>
                  </Tooltip>
                </div>
                <p>{{page.create_date}}</p>
              </div>
            </div>
            <div class="footer">
              <p class="float-left">{{ $PnUtil.cutString(page.name, 10) }}</p>
              <p class="float-right">
                <Icon type="ios-radio-button-on" :style="{color: page.publish == '1' ? '#4caf50':'#9e9e9e'}"/>
                {{ page.publish == '1' ? '已发布' : '未发布' }}
              </p>
              <div class="clearfix"></div>
            </div>
          </div>
        </i-col>
      </Row>
      <div class="none-alert" v-if="pageList.length == 0">
        <Icon type="ios-alert-outline" size="150"/>
        <p>找不到相关页面数据</p>
        <Button type="primary" v-show="pageParam.project_id" @click="openProject">进入设计器</Button>
      </div>
    </div>

    <ProjectForm ref="projectForm" @refreshDataList="loadProjects"></ProjectForm>

    <Modal
        v-model="importPageModalVisible"
        title="导入页面"
        :footer-hide="true">
      <ImportPage ref="importPageModal" @upload-success="importPageSuccessHandle"></ImportPage>
    </Modal>

    <ProjectDeveloperList ref="projectDeveloperList"
                          :show="projectDeveloperListVisible"
                          @cancel="projectDeveloperListVisible = false"></ProjectDeveloperList>

    <ReleasePageFormModal ref="releasePageFormModal"
                          :show="releasePageFormModalVisible"
                          @cancel="releasePageFormModalCancelHandle"></ReleasePageFormModal>

  </div>
</template>

<script>
import ProjectForm from './ProjectForm'
import ProjectDeveloperList from "./ProjectDeveloperList";
import ImportPage from '../../admin/page/ImportPage'
import ReleasePageFormModal from '@/views/components/designer/common/ReleasePageFormModal'

import ManageMixin from '../../../../mixin/ManageMixin'

import {createHelpers} from 'vuex-map-fields';

const {mapFields} = createHelpers({
  getterType: 'manage/getField',
  mutationType: 'manage/updateField',
});

const defaultPageParam = {
  project_id: '',
  name: '',
  develop_canvas: '',
  publish: ''
}

export default {
  name: 'ProjectManage',
  mixins: [ManageMixin],
  components: {
    ProjectForm,
    ProjectDeveloperList,
    ImportPage,
    ReleasePageFormModal
  },
  data() {
    return {
      currentUser: JSON.parse(localStorage.getItem('current_user')),
      currentTopProjectId: localStorage.getItem('currentTopProjectId'),
      loading: false,
      projectDeveloperListVisible: false,
      releasePageFormModalVisible: false,
      importPageModalVisible: false,

      statisticsData: {
        projectTotalCount: 0,
        pageTotalCount: 0
      },
      projectList: [],
      pageParam: this.$PnUtil.deepClone(defaultPageParam),
      pageList: []
    }
  },
  mounted() {
    this.loadProjects().then(() => {
      if (this.projectList.length > 0) {
        this.pageParam.project_id = this.projectList[0].id
        this.loadPages()
      }
    })

    if (this.currentUser.role_code == 'ROLE_ADMIN') {
      this.loadStatisticsData()
    }
  },
  methods: {

    developCanvasIcon(develop_canvas) {
      switch (develop_canvas) {
        case 'AbsoluteLayoutCanvas':
          return 'iconfont icon-absolute-layout'
        case 'ReactiveLayoutCanvas':
          return 'iconfont icon-reactive-layout'
        case 'FormLayoutCanvas':
          return 'iconfont icon-form-layout'
      }
      return ''
    },

    developCanvasName(develop_canvas) {
      switch (develop_canvas) {
        case 'AbsoluteLayoutCanvas':
          return '绝对布局'
        case 'ReactiveLayoutCanvas':
          return '响应式栅格布局'
        case 'FormLayoutCanvas':
          return '表单布局'
      }
      return ''
    },

    loadProjects() {
      let promise = new Promise((resolve, reject) => {
        this.$PnApi.ProjectApi.getMyProjects().then(result => {
          this.projectList = result.data.payload
          resolve()
        })
      })
      return promise
    },

    loadPages() {
      this.loading = true
      this.$PnApi.PageApi.getAllPage(this.pageParam).then(result => {
        this.pageList = result.data.payload
        this.loading = false
      })
    },

    loadStatisticsData() {
      this.$PnApi.StatisticsApi.getProjectTotalCount().then(result => {
        this.statisticsData.projectTotalCount = result.data.payload
      });
      this.$PnApi.StatisticsApi.getPageTotalCount().then(result => {
        this.statisticsData.pageTotalCount = result.data.payload
      })
    },

    openProjectForm(type, id) {
      this.$refs.projectForm.init(type, id)
    },

    deleteProject() {
      this.$Modal.confirm({
        title: '提醒',
        content: '删除工程会级联删除工程下的所有页面，确认执行吗？',
        onOk: () => {
          this.$PnApi.ProjectApi.deleteProject(this.pageParam.project_id).then(result => {
            if (result.data.success) {
              this.pageParam = this.$PnUtil.deepClone(defaultPageParam)
              this.$refs.projectSelect.clearSingleSelect()
              this.loadProjects();
              this.loadPages();
              this.$Message.success(result.data.message)
            }else {
              this.$Message.error(result.data.message)
            }
          });
        }
      });
    },

    openProject() {
      this.$PnUtil.openPageToBlank('/designer', {project_id: this.pageParam.project_id});
    },

    openPageDesigner (page_id) {
      this.$PnUtil.openPageToBlank('/designer', {project_id: this.pageParam.project_id, page_id: page_id});
    },

    otherDropdownClickHandle(name) {
      if (name == 'editProject') {
        this.openProjectForm('edit', this.pageParam.project_id)
      } else if (name == 'openImportPage') {
        this.importPageModalVisible = !this.importPageModalVisible;
        this.$refs.importPageModal.initProjectId(this.pageParam.project_id)
      } else if (name == 'openProjectDeveloperList') {
        this.projectDeveloperListVisible = !this.projectDeveloperListVisible;
        this.$refs.projectDeveloperList.init(this.pageParam.project_id)
      } else if (name == 'deleteProject') {
        this.deleteProject()
      }
    },

    importPageSuccessHandle() {
      this.importPageModalVisible = !this.importPageModalVisible;
      this.loadPages()
    },

    clearSearch() {
      this.pageParam.name = ''
      this.pageParam.develop_canvas = ''
      this.pageParam.publish = ''
      this.loadPages()
    },

    previewPage(pageId, pagePath) {
      this.$PnApi.DesignerApi.getDesignerData(pageId).then(result => {
        let pageMetadata = result.data.payload;
        pageMetadata.layout = JSON.parse(pageMetadata.layout);
        pageMetadata.theme_json = JSON.parse(pageMetadata.theme_json);
        localStorage.setItem('previewPageMetadata', JSON.stringify(pageMetadata));
        this.$PnUtil.openPageToBlank(pagePath, {preview: 'true'});
      });
    },

    openReleasePageFormModal(pageId) {
      this.$PnApi.PageApi.getPageById(pageId).then(result => {
        this.releasePageFormModalVisible = !this.releasePageFormModalVisible
        let pageMetadata = result.data.payload
        if (pageMetadata.theme_json) {
          pageMetadata.theme_json = JSON.parse(pageMetadata.theme_json);
        }
        pageMetadata.layout = JSON.parse(pageMetadata.layout);
        this.$refs.releasePageFormModal.init(pageMetadata)
      })
    },

    releasePageFormModalCancelHandle() {
      this.releasePageFormModalVisible = false
      this.loadPages()
    },

    exportPage(pageId) {
      this.$Modal.confirm({
        title: '确认',
        content: '特别提醒：不要修改导出的文件的文件名，否则将无法在导入时正常进行解析',
        onOk: () => {
          let url = window.g.AXIOS_BASE_URL + '/page/exportPage?pageId=' + pageId;
          this.$PnUtil.asyncHref(url, 'page_' + pageId)
        }
      })
    },

    copyLink(path) {
      let cont = window.location.protocol + '//' + window.location.host + window.g.PROJECT_ROOT_NAME + path;
      this.$PnUtil.copyToClipboard(cont);
      this.$Message.success('页面链接（' + cont + '）复制成功')
    },

    copyPage(pageId) {
      this.$Modal.confirm({
        title: '确认',
        content: '确定拷贝此页面至当前工程下吗？',
        onOk: () => {
          this.$PnApi.PageApi.copyPage(this.pageParam.project_id, pageId).then(result => {
            if (result.data.success) {
              this.$Message.success(result.data.message);
              this.loadPages()
            } else {
              this.$Message.error(result.data.message);
            }
          })
        }
      });
    },

    deletePage(pageId) {
      this.$Modal.confirm({
        title: '提醒',
        content: '确认删除此页面吗？',
        onOk: () => {
          this.$PnApi.PageApi.deletePage(pageId).then(result => {
            if (result.data.success) {
              this.$Message.success(result.data.message)
              this.loadPages();
            } else {
              this.$Message.error(result.data.message)
            }
          })
        }
      });
    },
  },
  computed: {
    /**
     * 当前选中的工程是否是协同工程
     */
    isSynergyProject() {
      let flag = false;
      for (let i=0; i<this.projectList.length; i++) {
        if (this.projectList[i].id == this.pageParam.project_id && this.projectList[i].user_id != this.currentUser.id) {
          flag = true
          break
        }
      }
      return flag
    }
  }
}
</script>

<style lang="less" scoped>
.project-manage {

  .project-toolbar {
    .page-search-wrap {
      padding: 8px;
      width: 100%;
      background: #424242;
      border-radius: 4px;
    }
  }

  .page-container {
    .page-card {
      width: 100%;
      border: 2px solid #424242;
      border-radius: 8px;
      background-color: #424242;
      position: relative;
      margin-bottom: 15px;

      &:hover {
        border-color: #2196f3;
        box-shadow: 2px 1px 20px #212121;
      }

      &:hover .img-wrap .operation-wrap {
        display: block;
      }

      .img-wrap {
        width: 100%;
        height: 140px;
        background-color: #212121;
        position: relative;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        padding: 10px;

        .default-img-icon {
          position: absolute;
          left: 50%;
          top: 50%;
          -webkit-transform: translate(-50%, -50%);
          -moz-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
          font-size: 80px;
          background-image: -webkit-gradient(linear, left top, left bottom, from(0deg), color-stop(#bbdefb), to(#2196f3));
          background-image: linear-gradient(0deg, #2196f3, #bbdefb);
          -webkit-background-clip: text;
          color: transparent;
        }

        .page-thumbnail {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }

        .layout-type {
          position: absolute;
          left: 0px;
          bottom: 0px;
          padding: 0px 8px 3px 8px;
          background-color: #212121;
          font-size: 14px;
          border-top: 2px solid #424242;
          border-right: 2px solid #424242;
          border-top-right-radius: 5px;
          z-index: 1;
        }

        .operation-wrap {
          display: none;
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0px;
          top: 0px;
          background-color: rgba(0, 0, 0, 0.8);
          border-top-left-radius: 8px;
          border-top-right-radius: 8px;
          padding: 25px 30px 30px 30px;
          text-align: center;
          p {
            margin-top: 10px;
          }
          .operation-btns-wrap {
            margin-top: 10px;

            .ivu-tooltip {
              &:first-child {
                margin-left: 0px;
              }

              margin-left: 8px;

              a {
                color: #fff;
                i {
                  position: relative;
                }

                &:hover {
                  color: #2196f3;
                }
              }
            }
          }
        }
      }

      .footer {
        width: 100%;
        background-color: #424242;
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
        padding: 12px 8px 12px 8px;
        position: relative;

        p {
          font-size: 13px;
        }
      }
    }
  }
}

.spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
